package com.dts.server.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dts.server.common.base.BaseAuthService;
import com.dts.server.common.base.BaseSession;
import com.dts.server.common.enums.ResultCode;
import com.dts.server.common.exception.CustomException;
import com.dts.server.common.result.ListResult;
import com.dts.server.common.util.PagerUtil;
import com.dts.server.db.dao.ProjectAuthMapper;
import com.dts.server.db.dao.ProjectMonitorMapper;
import com.dts.server.dbutil.entity.ProjectAuth;
import com.dts.server.dbutil.entity.ProjectAuthKey;
import com.dts.server.dbutil.entity.ProjectMonitor;
import com.dts.server.query.AuthQuery;

@Service
@Transactional
public class ProjectAuthService extends BaseAuthService {
	
	@Resource
	private ProjectAuthMapper projectAuthMapper;
	
	private ProjectMonitorMapper projectMonitorMapper;
	
	/**
	 * 查询项目授权用户列表
	 * @param param
	 * @param session
	 * @return 
	 * @throws Exception
	 */
	public ListResult<ProjectAuth> query(AuthQuery param, BaseSession session) throws Exception {
		if(!vaildProjectEditAuth(param.getProjectId(), session)){
			throw new CustomException(ResultCode.S_UNAUTH_ERROR);
		}
		Integer totalCount = projectAuthMapper.queryCount(param);
		if (totalCount <= 0) {
			throw new CustomException(ResultCode.S_NULL_ERROR);
		}
		param.setStart(PagerUtil.MathStart(param.getPagenum(), totalCount));
		List<ProjectAuth> list = projectAuthMapper.query(param);
		return new ListResult<ProjectAuth>(totalCount, list);
	}
	
	/**
	 * 新增项目授权
	 * @param projectAuth
	 * @param session
	 * @return
	 * @throws Exception
	 */
	public boolean add(ProjectAuth auth, BaseSession session) throws Exception {
		if(!vaildProjectEditAuth(auth.getProjectId(), session)){
			throw new CustomException(ResultCode.S_UNAUTH_ERROR);
		}
		return projectAuthMapper.add(auth) > 0;
	}
	
	/**
	 * 编辑项目授权信息
	 * @param auth
	 * @param session
	 * @return
	 * @throws Exception
	 */
	public boolean edit(ProjectAuth auth, BaseSession session) throws Exception {
		if(!vaildProjectEditAuth(auth.getProjectId(), session)){
			throw new CustomException(ResultCode.S_UNAUTH_ERROR);
		}
		return projectAuthMapper.edit(auth) > 0;
	}

	/**
	 * 删除项目授权用户
	 * @param id
	 * @param session
	 * @return
	 * @throws Exception
	 */
	public boolean delete(ProjectAuthKey id, BaseSession session) throws Exception {
		if(!vaildProjectEditAuth(id.getProjectId(), session)){
			throw new CustomException(ResultCode.S_UNAUTH_ERROR);
		}
		return projectAuthMapper.delete(id) > 0;
	}
	
	/**
	 * 验证是否有项目中某个监听的权限
	 * @param monitorId
	 * @param session
	 * @return
	 * @throws Exception
	 */
	public boolean vaildMonitorAuth(Integer monitorId, BaseSession session) throws Exception {
		ProjectMonitor monitor = projectMonitorMapper.selectById(monitorId);
		return vaildProjectAuth(monitor.getProjectId(), session);
	}
}
